/**
 * 
 * A map is a collection of tiles
 * It has dead tiles and existing tiles
 * 
 * You can update them, tell them what their neighbours are
 * or just access the tile list directly
 * 
 * @author Andrew
 * @creator Andrew
 */
public class Map {
	
	// A list of All tiles in the map
	public TileObject[] tileList;
	
	// A list of Tiles in the map which are still "on screen"
	public TileObject[] existingTiles;
	
	// A list of tiles in the map which have been "destroyed"
	public TileObject[] deadTiles;
	
	// Constructor
	public Map(TileObject[] tileListInput) {
		this.tileList = tileListInput;
	}
	
	// Function which updates the existingTiles and deadTiles variables with
	// new data automagically
	public void update() {
		int liveCount = 0;
		int deadCount = 0;
		for(int i = 0;i<tileList.length;i++) {
			if(tileList[i].getExist()) liveCount++;
			else deadCount++;
		}
		existingTiles = new TileObject[liveCount];
		deadTiles = new TileObject[deadCount];
		liveCount = 0;
		deadCount = 0;
		for(int i = 0; i<tileList.length;i++) {
			if(tileList[i].getExist()) { 
				existingTiles[liveCount] = tileList[i];
				liveCount++;
			}
			else {
				deadTiles[deadCount] = tileList[i];
				deadCount++;
			}
		}
		
	}
	
	// Reset the neighbours of all tiles in the list
	public void resetAll() {
		for(int i = 0;i<tileList.length;i++) {
			tileList[i].reset();
		}
	}
	
	// Sets the Neighbours of every tile in the map.
	// Highly inefficient but works. Run once at the start.
	public void setNeighbours(int sWidth, int sHeight) {
		for(int i = 0;i<tileList.length;i++) {
			for(int j = 0;j<tileList.length;j++) {
				if(tileList[j].getX() == tileList[i].getX() &&
				   tileList[j].getY() == tileList[i].getY() + 16) {
					tileList[i].setTileTop(tileList[j]);
				}
				if(tileList[j].getX() == tileList[i].getX() &&
						   tileList[j].getY() == tileList[i].getY() - 16) {
							tileList[i].setTileBottom(tileList[j]);
						}
				if(tileList[j].getX() == tileList[i].getX()+16 &&
						   tileList[j].getY() == tileList[i].getY()) {
							tileList[i].setTileRight(tileList[j]);
						}
				if(tileList[j].getX() == tileList[i].getX()-16 &&
						   tileList[j].getY() == tileList[i].getY()) {
							tileList[i].setTileLeft(tileList[j]);
						}
			}
			tileList[i].update();
		}
	}
}